define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'bootstrap-datetimepicker'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'room/index' + location.search,
                    add_url: 'room/add',
                    edit_url: 'room/edit',
                    del_url: 'room/del',
                    multi_url: 'room/multi',
                    import_url: 'room/import',
                    table: 'room',
                }
            });

            var table = $("#table");

            table.on('post-common-search.bs.table', function (event, table) {
                var form = $("form", table.$commonsearch);
                $("input[name='store_id']", form).addClass("selectpage")
                    .data("source", "store/index")
                    .data("primaryKey", "id").data("field", "store_name");
                Form.events.cxselect(form);
                Form.events.selectpage(form);
            });

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'), operate: false},
                        {field: 'store_id', title: __('Store_id'), operate: '=', visible: false},
                        {field: 'store.store_name', title: __('Store_id'), operate: '='},
                        {field: 'room_name', title: __('Room_name'), operate: 'LIKE'},
                        {field: 'room_area', title: __('Room_area'), operate: false},
                        {field: 'room_personnum', title: __('Room_personnum'), operate: false},
                        {field: 'room_bannerimage', title: __('Room_bannerimage'), operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image},
                        {field: 'status', title: __('Status'), formatter: Table.api.formatter.status, searchList: {normal: __('Normal'), hidden: __('Hidden')}},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'preview_btn',
                                    text: '预览租用时间',
                                    classname: 'btn btn-xs btn-info btn-dialog',
                                    url: function (row) {
                                        return Fast.api.fixurl('room/previewtime?id=' + row.id)
                                    },
                                    extend: "data-area='[\"80%\", \"80%\"]'",
                                },
                                {
                                    name: 'zy_button',
                                    text: '设置租用时间',
                                    classname: 'btn btn-xs btn-info btn-dialog',
                                    icon: 'fa fa-check-square',
                                    url: function (row) {
                                        return Fast.api.fixurl('room/renttime?id=' + row.id)
                                    },
                                    extend: "data-area='[\"50%\", \"80%\"]'",
                                },
                                {
                                    name: 'copy_button',
                                    text: '复制',
                                    classname: 'btn btn-xs btn-info btn-ajax',
                                    icon: 'fa fa-check-square',
                                    url: function (row) {
                                        return Fast.api.fixurl('room/ajaxCopy?id=' + row.id)
                                    },
                                    success: function (data, ret) {
                                        // Layer.alert(ret.msg + ",返回数据：" + JSON.stringify(data));
                                        table.bootstrapTable('refresh');
                                        //如果需要阻止成功提示，则必须使用return false;
                                        //return false;
                                    },
                                    error: function (data, ret) {
                                        console.log(data, ret);
                                        Layer.alert(ret.msg);
                                        return false;
                                    }
                                }
                            ],
                            formatter: Table.api.formatter.operate}
                    ]
                ],
                searchFormVisible: true,
                search: false,
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            $('#search-homeid').on('click', function () {
                var uuid = $('#c-yunding_elemetor_uuid').val()
                $.ajax({
                    url: "room/ajaxGetHomeId",
                    type: 'post',
                    dataType: 'json',
                    data: {uuid},
                    success: function (ret) {
                        if (ret.hasOwnProperty("code")) {
                            var data = ret.hasOwnProperty("data") && ret.data != "" ? ret.data : "";
                            if (ret.code === 1) {
                                $('#c-yunding_homeid').val(ret.data['homeid'])
                            } else {
                                Backend.api.toastr.error(ret.msg);
                            }
                        }
                    }, error: function (e) {
                        Backend.api.toastr.error(e.message);
                    }
                });
            })
            Controller.api.bindevent();
        },
        edit: function () {
            $('#search-homeid').on('click', function () {
                var uuid = $('#c-yunding_elemetor_uuid').val()
                $.ajax({
                    url: "room/ajaxGetHomeId",
                    type: 'post',
                    dataType: 'json',
                    data: {uuid},
                    success: function (ret) {
                        if (ret.hasOwnProperty("code")) {
                            var data = ret.hasOwnProperty("data") && ret.data != "" ? ret.data : "";
                            if (ret.code === 1) {
                                $('#c-yunding_homeid').val(ret.data['homeid'])
                            } else {
                                Backend.api.toastr.error(ret.msg);
                            }
                        }
                    }, error: function (e) {
                        Backend.api.toastr.error(e.message);
                    }
                });
            })
            Controller.api.bindevent();
        },
        previewtime: function () {
            const option = {
                // 支持引入组件
                setup(){
                    const {ref,onMounted, nextTick, watch} = Vue;
                    const valueData = ref(new Date());
                    const curDate = dateFormat('YYYY-mm-dd', new Date()); 
                    const startDate = ref('');
                    const showPill = ref(false)
                    const queryDate = ref('');
                    const dialogTitle = ref('');
                    const pillData = ref([])
                    const calendarData = ref([
                        { months: ['03', '04'],days: ['15'],things: '开放时段：09:00-12:00,13:00-17:00' },
                    ])
                    onMounted(()=>{
                        loadPills()
                        Controller.api.bindevent();  
                    })
                    watch(valueData, (newVal, oldVal) => {
                      const newd = this.dateFormat('YYYY-mm-dd',newVal)
                      const newdate = this.dateFormat('YYYY-mm',newVal)
                      const olddate = this.dateFormat('YYYY-mm',oldVal)
                      console.log('newVal =>', newdate)
                      console.log('oldVal =>', olddate)
                      if (newdate !== olddate) {
                          queryDate.value = newd
                          loadPills()
                      }
                    })
                    function loadPills() {
                        const roomId = $('#room_id').val()
                        $.ajax({
                            url: `room/ajaxGetPreview`,
                            type: 'post',
                            dataType: 'json',
                            data: {
                              date: queryDate.value,
                              id: roomId
                            },
                            success: function (ret) {
                                if (ret.hasOwnProperty("code")) {
                                    var data = ret.hasOwnProperty("data") && ret.data != "" ? ret.data : "";
                                    if (ret.code === 1) {
                                        calendarData.value = ret.data
                                    } else {
                                        Backend.api.toastr.error(ret.msg);
                                    }
                                }
                            }, error: function (e) {
                                Backend.api.toastr.error(e.message);
                            }
                        });
                    }
                    function handleClick(d) {
                        console.log('handleClick =>', d)
                        dialogTitle.value = d['day'] + ' 时段设置查看' 
                        showPill.value = true
                        const roomId = $('#room_id').val()

                        $.ajax({
                            url: `room/ajaxGetPills`,
                            type: 'post',
                            dataType: 'json',
                            data: {
                              date: d['day'],
                              id: roomId,
                            },
                            success: function (ret) {
                                if (ret.hasOwnProperty("code")) {
                                    var data = ret.hasOwnProperty("data") && ret.data != "" ? ret.data : "";
                                    if (ret.code === 1) {
                                        pillData.value = ret.data
                                    } else {
                                        Backend.api.toastr.error(ret.msg);
                                    }
                                }
                            }, error: function (e) {
                                Backend.api.toastr.error(e.message);
                            }
                        });
                    }
                    /*
                    nextTick(() => {
                      // 点击上个月
                      let prevBtn = document.querySelector('.el-calendar__button-group .el-button-group>button:nth-child(1)');
                      prevBtn.addEventListener('click', () => {
                        queryDate.value = this.dateFormat('YYYY-mm-dd',valueData.value)
                        loadPills();
                      })
                      // 点击今天
                      let currBtn = document.querySelector('.el-calendar__button-group .el-button-group>button:nth-child(2)');
                      currBtn.addEventListener('click', () => {
                        queryDate.value = this.dateFormat('YYYY-mm-dd',valueData.value)
                        loadPills();
                      })
                      // 点击下个月
                      let nextBtn = document.querySelector('.el-calendar__button-group .el-button-group>button:nth-child(3)');
                      nextBtn.addEventListener('click', () => {
                        queryDate.value = this.dateFormat('YYYY-mm-dd',valueData.value)
                        loadPills();
                      })
                    })
                    */
                    return {
                        valueData,
                        calendarData,
                        handleClick,
                        pillData,
                        showPill,
                        dialogTitle,
                    };
                }
                
            }
            createApp('app', option)
        },
        renttime: function () {
            const tabs = {

                setup(){
                    const {ref, onMounted} = Vue;
                    const activeName = ref('first')
                    // 是否占用 0=不可对外开放 1=可对外开放
                    const isOpen = ref('1')
                    // global
                    const price = ref(0)
                    const times = ref([0, 24])
                    const inputs = ref([])
                    // week
                    const weeks = ref([
                      { name: 'week1', showName: '星期一' },
                      { name: 'week2', showName: '星期二' },
                      { name: 'week3', showName: '星期三' },
                      { name: 'week4', showName: '星期四' },
                      { name: 'week5', showName: '星期五' },
                      { name: 'week6', showName: '星期六' },
                      { name: 'week7', showName: '星期日' },
                    ])

                    const activeNameWeek = ref('week1')
                    const showWeekSet = ref(true)
                    const showWeekList = ref(false)
                    const weekList = ref([])
                    const priceWeek = ref(0)
                    const timesWeek = ref([0, 24])
                    const inputsWeek = ref({})
                    const totalInputsWeek = ref({})

                    // date
                    const priceDate = ref(0)
                    const timesDate = ref([0, 24])
                    const inputsDate = ref([])
                    const open = ref('0')
                    const date1 = ref('')
                    const date2 = ref('')

                    onMounted(() =>{
                      parseRentTime()
                      initWeekRoomSetting()
                      initDateRoomSetting()
                      Controller.api.bindevent();
                    })
                    
                    // common
                    function createRentTimeData(rentTimeData) {
                      const ginputs = []
                      for (let i in rentTimeData) {
                        let oldPill = rentTimeData[i]
                        let pill = { start: '', end: '', price: 0, key: '' }
                        pill['start'] = oldPill['start'] 
                        pill['end'] = oldPill['end']
                        pill['price'] = parseInt(oldPill['price'])
                        pill['key'] = oldPill['start']
                        if (oldPill['is_open'] === undefined) {
                          pill['is_open'] = '1'
                        } else {
                          pill['is_open'] = oldPill['is_open']
                        }
                        ginputs.push(pill)
                      }
                      return ginputs
                    }

                    function createInputs(start, end, price, isOpen) {
                        // 暂不能使用对象形式，因为会在v-for循环时显示顺序非插入顺序
                        const ginputs = []
                        for (let i = start; i < end; i = i + 0.5) {
                          let ival = i.toString()
                          let ivals = ival.split('.')
                          let tmpival = parseInt(ivals[0])
                          if (tmpival < 10) {
                            ivals[0] = '0' + ivals[0]
                          }
                          let istart = ''
                          let iend = ''
                          let pill = { start: '', end: '', price: price }
                          if (ivals.length > 1) {
                            istart = ivals[0] + ':30'
                            iend = ivals[0] + ':59'
                          } else {
                            istart = ivals[0] + ':00'
                            iend = ivals[0] + ':29'
                          }
                          pill['start'] = istart
                          pill['end'] = iend
                          pill['is_open'] = isOpen
                          pill['key'] = istart
                          ginputs.push(pill)
                        }

                        return ginputs
                    }

                    function removeRentTimeKey(rentTimeTmp) {
                        const rentTimes = [] 
                        for (let r in rentTimeTmp) {
                          let pill = rentTimeTmp[r]
                          delete pill['key']
                          rentTimes.push(pill)
                        }
                        
                        return rentTimes
                    }

                    function deletePill(ginputs, k) {
                        const newInputs = []
                        for (let i in ginputs) {
                          let input = ginputs[i] 
                          if (input['key'] != k) {
                            newInputs.push(input)
                          }
                        }

                        return newInputs
                    }

                    function parseRentTime() {
                      const rentTimeStr = $('#rent_time').val()
                      let rentTime = []
                      if (rentTimeStr.length > 2) {
                        rentTime = JSON.parse(rentTimeStr)
                      }
                      inputs.value = createRentTimeData(rentTime)
                    }

                    function handleClickTab(tab, e) {
                        console.log(tab.props.name)
                    }

                    // global 
                    function onCreateGlobal() {
                        const start = times.value[0] 
                        const end = times.value[1]
                        inputs.value = createInputs(start, end, price.value, isOpen.value)
                    }
                    function formatTime(val) {
                        val = val.toString()
                        let vals = val.split('.')
                        if (vals.length > 1) {
                            return vals[0]  + '点30分'
                        }
                        return vals[0] + '点'
                    }
                    function onSubmit() {
                        const rentTimes = removeRentTimeKey(inputs.value)
                        const roomId = $('#room_id').val()
                        Fast.api.ajax({
                            url: `room/saveRentTime`,
                            type: 'POST',
                            data: {
                              rent_time: JSON.stringify(rentTimes),
                              save_type: 'global',
                              id: roomId
                            }
                        }, function (ret, res) {
                            Fast.api.close()
                        }, function (ret, res) { }) 
                    }
                    function onDeletePill(k) {
                        inputs.value = deletePill(inputs.value, k)
                    }
                    function clearGlobalData() {
                        inputs.value = {}
                        price.value = 0 
                        times.value = [0, 24]
                    }
                    // Week
                    function initWeekRoomSetting() {
                        const rentTimeStr = $('#week_rent_time').val()
                        let weekRentTimeData = {}
                        if (rentTimeStr.length > 2) {
                          weekRentTimeData = JSON.parse(rentTimeStr)
                        }
                        getRoomSetting(weekRentTimeData)
                        getWeekRentTime('week1')
                    }
                    function getRoomSetting(weekRentTimeData) {
                        const tmpW = weeks.value
                        const tmpWeekList = []
                        for(i in tmpW) {
                          let tmpWeek = tmpW[i]
                          if (weekRentTimeData[tmpWeek['name']] !== undefined && weekRentTimeData[tmpWeek['name']].length > 0) {
                            tmpWeek['isSet'] = 1
                          } else {
                            tmpWeek['isSet'] = 0
                          }
                          tmpWeekList.push(tmpWeek)
                        }
                        weekList.value = tmpWeekList
                        weeks.value = tmpWeekList
                        totalInputsWeek.value = weekRentTimeData 
                    }
                    function onSetWeek(w) {
                        showWeekList.value = false
                        showWeekSet.value = true
                        activeNameWeek.value = w 
                        getWeekRentTime(w) 
                    }
                    function onCreateWeek() {
                        const start = timesWeek.value[0] 
                        const end = timesWeek.value[1]
                        inputsWeek.value = createInputs(start, end, priceWeek.value, isOpen.value)
                    }
                    function onClearWeek() {
                        inputsWeek.value = []
                    }
                    function formatTimeWeek(val) {
                        val = val.toString()
                        let vals = val.split('.')
                        if (vals.length > 1) {
                            return vals[0]  + '点30分'
                        }
                        return vals[0] + '点'
                    }
                    function onSubmitWeek() {
                        const rentTimes = removeRentTimeKey(inputsWeek.value)
                        const weekRentTimes = totalInputsWeek.value
                        weekRentTimes[activeNameWeek.value] = rentTimes
                        const roomId = $('#room_id').val()
                        Fast.api.ajax({
                            url: `room/saveRentTime`,
                            type: 'POST',
                            data: {
                              week_rent_time: JSON.stringify(weekRentTimes),
                              save_type: 'week',
                              id: roomId
                            }
                        }, function (ret, res) {
                            getRoomSetting(weekRentTimes)
                        }, function (ret, res) { }) 
                    }
                    function clearWeekData() {
                        inputsWeek.value = {}
                        priceWeek.value = 0 
                        timesWeek.value = [0, 24]
                    }
                    function onDeletePillWeek(k) {
                        inputsWeek.value = deletePill(inputsWeek.value, k)
                    }

                    function handleClickTabWeek(tabw, e) {
                        // 查找对应星期的值 
                        const week = tabw.props.name
                        getWeekRentTime(week)
                    }
                    
                    function getWeekRentTime(w) {
                        clearWeekData()
                        const weekRentTimeData = totalInputsWeek.value
                        if (weekRentTimeData[w] !== undefined) {
                            inputsWeek.value = createRentTimeData(weekRentTimeData[w])
                        }
                    }
                    
                    // date
                    function initDateRoomSetting() {
                        const rentTimeStr = $('#date_rent_time').val()
                        const dateSettingStr = $('#date_setting').val()
                        let dateRentTimeData = []
                        if (rentTimeStr.length > 2) {
                          dateRentTimeData = JSON.parse(rentTimeStr)
                        }
                        inputsDate.value = createRentTimeData(dateRentTimeData)
                        if (dateSettingStr.length > 2) {
                          const dateSetting = JSON.parse(dateSettingStr)
                          date1.value = dateSetting['date1']
                          date2.value = dateSetting['date2']
                          open.value = dateSetting['open']
                        }
                    }
                    function onCreateDate() {
                        const start = timesDate.value[0] 
                        const end = timesDate.value[1]
                        inputsDate.value = createInputs(start, end, priceDate.value, isOpen.value)
                    }
                    function formatTimeDate(val) {
                        val = val.toString()
                        let vals = val.split('.')
                        if (vals.length > 1) {
                            return vals[0]  + '点30分'
                        }
                        return vals[0] + '点'
                    }
                    function onSubmitDate() {
                        const rentTimes = removeRentTimeKey(inputsDate.value)
                        const roomId = $('#room_id').val()
                        if (date1.value === '' || date1.value === null) {
                          $('#startdate').focus()
                          $('#err').html('开始日期必须填写！')
                          return
                        }
                        if (date2.value === '' || date2.value === null) {
                          $('#enddate').focus()
                          $('#err').html('结束日期必须填写！')
                          return
                        }
                        if (date1.value > date2.value) {
                          $('#err').html('开始日期不能大于结束日期！')
                          $('#enddate').focus()
                          return
                        }
                        const dateSetting = {
                          open: open.value,
                          date1: date1.value,
                          date2: date2.value,
                        }
                        Fast.api.ajax({
                            url: `room/saveRentTime`,
                            type: 'POST',
                            data: {
                              date_rent_time: JSON.stringify(rentTimes),
                              date_setting: JSON.stringify(dateSetting),
                              save_type: 'date',
                              id: roomId
                            }
                        }, function (ret, res) {
                            Fast.api.close()
                        }, function (ret, res) { }) 
                    }
                    function onDeletePillDate(k) {
                        inputsDate.value = deletePill(inputsDate.value, k)
                        const inputs = inputsDate.value
                        if (Object.keys(inputs).length === 0) {
                          open.value = '0'
                          clearDateData()
                        }
                    }
                    function clearDateData() {
                        inputsDate.value = {}
                        priceDate.value = 0 
                        timesDate.value = [0, 24]
                    }

                    return {
                        activeName,
                        handleClickTab,
                        // global
                        price,
                        times,
                        inputs,
                        onCreateGlobal,
                        formatTime,
                        onSubmit,
                        onDeletePill,
                        clearGlobalData,
                        // Week
                        weeks,
                        activeNameWeek,
                        weekList,
                        showWeekList, 
                        showWeekSet,
                        onSetWeek,
                        priceWeek,
                        timesWeek,
                        onCreateWeek,
                        formatTimeWeek,
                        inputsWeek,
                        onSubmitWeek,
                        onClearWeek,
                        onDeletePillWeek,
                        handleClickTabWeek,
                        clearWeekData,
                        // date
                        priceDate,
                        timesDate,
                        inputsDate,
                        open,
                        date1,
                        date2,
                        onCreateDate,
                        formatTimeDate,
                        onSubmitDate,
                        onDeletePillDate,
                        clearDateData,
                    }
                }
                
            }
            createApp('tabs', tabs)

        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});
